//
//  NetWorkTool.swift
//  swift微博
//
//  Created by CC on 16/2/28.
//  Copyright © 2016年 CC. All rights reserved.
//

import UIKit
import AFNetworking

class NetWorkTool : NSObject {
    
    let afnManager : AFHTTPSessionManager
    
    //单例
    static let sharedInstance: NetWorkTool = NetWorkTool()
    
    //private表示私有方法,除这个文件外的其它类是不知道这个方法的
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        //添加处理文本格式
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    // MARK: - Oauth授权相关
    let client_id = "3621983475"
    let client_secret = "bcb84246a21dfca580bd65bc314eb664"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    /// 获取oauth授权的登录界面地址
    func oauthLoginUrl() -> NSURL {
        let urlString = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    
    /// 获取Access Token
    func loadAccessToken(code: String , tokenGot: (rensponse : [String : AnyObject]?  , error : NSError?) -> () ){
        // 1.请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        
        // 发送POST请求（默认异步不能return，用闭包返回）
        afnManager.POST(urlString, parameters: parameters, progress:nil, success: { (_, response) -> Void in
            let dict = response as? [String: AnyObject]
            //调用闭包
            tokenGot(rensponse: dict, error :nil)
            }) { (_, error) -> Void in
            tokenGot(rensponse: nil , error :error)
        }
    }
}

